/*
-------------------------------------------------

	XML.mm

	Dmitriy Kuzmenko (Dgut)

-------------------------------------------------
*/

#include "XML.h"
#include "File.h"

namespace Autumn
{

XML::XML( void )
{
}

XML::~XML( void )
{
}

pugi::xml_document * const XML::Load( const char * name, bool magic )
{
	FILE * stream = gFile.Open( name, "rb" );
	if( !stream )
		return false;

	fseek( stream, 0, SEEK_END );
	const int LENGTH = ftell( stream );
	fseek( stream, 0, SEEK_SET );
	char * buffer = new char[ LENGTH ];
	fread( buffer, LENGTH, 1, stream );
	
	if( magic )
		for( int i = 0; i < LENGTH; i++ )
			buffer[ i ] ^= 0x55;

	fclose( stream );

	pugi::xml_document * doc = new pugi::xml_document();

	if( !doc->load_buffer( buffer, LENGTH ) )
	{
		delete[] buffer;
		delete doc;
		return 0;
	}

	delete[] buffer;
	return doc;
}

const bool XML::Save( pugi::xml_document * doc, const char * name, bool magic )
{
	class Writer : public pugi::xml_writer
	{
	public:
		Writer( const char * name, bool magic ) :
			stream	( gFile.Open( name, "wb" ) ),
			magic	( magic )
		{
		}

		virtual ~Writer( void )
		{
			fclose( stream );
		}

		FILE * stream;
		bool magic;

		virtual void write( const void * data, size_t size )
		{
			if( magic )
			{
				for( int i = 0; i < size; i++ )
					putc( ( ( const char * )data )[ i ] ^ 0x55, stream );
				return;
			}
			
			fwrite( data, size, 1, stream );
		}
	};

	Writer writer( name, magic );
	if( !writer.stream )
		return false;

	doc->save( writer );
	return true;
}

}	// namespace Autumn